package edu.sctu;


import edu.sctu.User;
import edu.sctu.UserDao;
import edu.sctu.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;

/**
 *删除用户Servlet
 */
public class UserDeleteServlet extends HttpServlet {

    DbUtil dbUtil = new DbUtil();
    UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session=request.getSession();
        //判断是否登录
        if (session.getAttribute("isLogin") == null){
            session.setAttribute("notLogin","请先登录！");
            response.sendRedirect("/login.jsp");//未登录则跳转到登录页面
        }else {
            userDelete(request,response);
        }

    }

    /**
     * 删除用户
     * @param request
     * @param response
     */
    private void userDelete(HttpServletRequest request, HttpServletResponse response){
        //用户更新表单的参数
        int userId = Integer.parseInt(request.getParameter("id"));
        String userName = request.getParameter("username");
        String password = request.getParameter("password");

        Connection connection = null;
        try {
            connection=dbUtil.getCon();
            User user = new User(userId,userName,password);//用户表单数据

            userDao.delete(connection,user);//删除
            response.sendRedirect("/userList");//删除成功后跳转到用户列表页面

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //数据库关闭
                dbUtil.closeCon(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}